package com.lz.dubbo.consumer.common.utils;

import org.apache.commons.collections.MapUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author yunnuo.yang
 * @Date 2020/9/25 19:11
 * @Description
 **/
public class SortUtil {

    /**
     * 对包含term的值进行排序
     *
     * @param datas     list<Map>数据
     * @param sortByKey 根据关键的key值的value进行排序
     * @param asc       是否升序 true 升序 ，false降序
     * @return
     */
    public static List<Map> sortTerm(List<Map> datas, String sortByKey, Boolean asc) {
        if (datas.size()==0){
            return datas;
        }
        List<Map> collect = datas.stream().map(el -> {
            String term = MapUtils.getString(el, sortByKey);
            int sort = DateUtils.getDateBetweenDiffer(DateUtils.getCurrentDate(),convertToDayUnit(DateUtils.getCurrentDate(), term));
            el.put("sort", sort);
            return el;
        }).sorted(Comparator.comparing(new Function<Map, Integer>() {
            @Override
            public Integer apply(Map map) {
                return Math.abs(Integer.valueOf(String.valueOf(map.get("sort"))));
            }
        })).collect(Collectors.toList());

        if (!asc) {
            Collections.reverse(collect);
            return collect;
        }
        return collect;
    }

    /**
     * 提供排序时使用
     *
     * @param dateString
     * @param term       D,W,M,Y
     * @return
     */
    public static String convertToDayUnit(String dateString, String term) {
        String unit = term.substring(term.length() - 1);
        Integer val = Double.valueOf(term.replace(unit, "")).intValue();
        if ("D".equalsIgnoreCase(unit)) {
            return DateUtils.addDate(dateString, val);
        } else if ("W".equalsIgnoreCase(unit)) {
            return DateUtils.addDate(dateString, val * 7);
        } else if ("M".equalsIgnoreCase(unit)) {
            return DateUtils.addMonth(dateString, val);
        } else if ("Y".equalsIgnoreCase(unit)) {
            return DateUtils.addYear(dateString, val);
        }
        return null;
    }


}
